//
//  AlipayEditAccountViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/11/7.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "AlipayEditAccountViewController.h"
#import "AlipayOSSModel.h"
#import "MyOSSClient.h"
#import <AliyunOSSiOS/OSSService.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import "UIImageView+WebCache.h"
#import "AccountViewController.h"

typedef void (^GetImgVSuccessBlock) (UIImage * image,NSString * imgName,NSData *ImageData );

@interface AlipayEditAccountViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>


@property (nonatomic,strong)UITextField * name_textField;
@property (nonatomic,strong)UITextField * zhanghao_textField;
@property (nonatomic,strong)UITextField * password_textField;
@property (nonatomic,strong)UIScrollView * SC;
@property (nonatomic,strong)UIButton *  btn1;

@property (nonatomic,strong)NSData *ImageData;
@property (nonatomic,strong)NSString * imageName;

@property (nonatomic,copy) GetImgVSuccessBlock ImgBlock;


@end

@implementation AlipayEditAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setProperty];
    [self createUI];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
}

-(void)setProperty{
    
    self.view.backgroundColor=RGB(255, 255, 255);
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    if ([_dataSource.paytype_id integerValue]==4) {
        self.baseVcTitle = @"编辑支付宝账户";
    }else{
        self.baseVcTitle = @"编辑微信账户";
    }
    
    
}

-(void)createUI{
    
    [self.rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    
    _SC=[[UIScrollView alloc]initWithFrame:CGRectMake(0, kStatusBarAndNavigationBarHeight, G_SCREENWIDTH, G_SCREENHEIGHT-kStatusBarAndNavigationBarHeight)];
    [self.view addSubview:_SC];
    CGFloat H = G_SCREENHEIGHT;
    if (G_SCREENHEIGHT<(20+6*90+400)) {
        H =20+6*90+400;
    }
    
    _SC.contentSize = CGSizeMake(G_SCREENWIDTH, H );
    
    UILabel * lab = [[UILabel alloc]init];
    [_SC addSubview:lab];
    [self setLab:lab withColor:RGB(30, 63, 89) andFont:12 andText:@"上传您的收款二维码" andTextAlignment:NSTextAlignmentLeft];
    lab.frame=CGRectMake(15, 20, G_SCREENWIDTH-30, 30);
    
    UIView * pictureView = [[UIView alloc]init];
    pictureView.backgroundColor = RGB(231, 235, 238);
    [self.SC addSubview:pictureView];
    pictureView.frame=CGRectMake(15, 50, G_SCREENWIDTH-30, 165);
    
    UIButton *  btn1 = [[UIButton alloc]init];
    [pictureView addSubview:btn1];
    //    btn1.imageView.size=CGSizeMake(22, 21) ;
    [btn1 setTitleColor:ThemeColor forState:UIControlStateNormal];
    [btn1 setTitle:@"选择上传二维码" forState:UIControlStateNormal];
    //    [btn1 setImage:[UIImage imageNamed:@"二维码icon"] forState:UIControlStateNormal];
    btn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn1.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    [btn1 addTarget:self action:@selector(selectedQRcode) forControlEvents:UIControlEventTouchUpInside];
    //    btn1.backgroundColor=MC_TEST_COLOR;
    //    btn1.frame=CGRectMake((G_SCREENWIDTH-150-30)/2.0, (165-40)/2.0, 150, 40);
    btn1.frame=CGRectMake(0, 0, G_SCREENWIDTH-30, 165);
    _btn1 = btn1;
    btn1.imageView.contentMode = UIViewContentModeScaleAspectFit;

    
    NSString * str=@"";
    
    
    if ([_dataSource.paytype_id integerValue]==4) {
        str = @"支付宝";
    }else{
        str = @"微信";
    }
    _name_textField = [[UITextField alloc]init];
    [self setText:@"姓名" andTF:_name_textField andIndex:0 andPlaceholder:@"请输入姓名" andKeyboardType:UIKeyboardTypeDefault];
    _zhanghao_textField = [[UITextField alloc]init];
    [self setText:[NSString stringWithFormat:@"%@账户",str] andTF:_zhanghao_textField andIndex:1 andPlaceholder:[NSString stringWithFormat:@"请输入%@账户",str] andKeyboardType:UIKeyboardTypeDefault];
    _password_textField = [[UITextField alloc]init];
    [self setText:@"资金密码" andTF:_password_textField andIndex:2 andPlaceholder:@"请输入资金密码" andKeyboardType:UIKeyboardTypeDefault];
    _password_textField.secureTextEntry = YES;
    
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.view  addGestureRecognizer:singleTapGesture];
    
    
    NSDictionary * account = _dataSource.account;
    
    _name_textField.text = [NSString stringWithFormat:@"%@",account[@"name"]];
    _zhanghao_textField.text = [NSString stringWithFormat:@"%@",account[@"account"]];

    NSString * URL = [NSString stringWithFormat:@"%@",account[@"qrcode_url"]];
//    _btn1 setImage:[UIImage im] forState:<#(UIControlState)#>

    WS(weakSelf);
    NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];
    UIImage *image = [[UIImage alloc]initWithData:imageData];
    if (imageData != nil) {


        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.btn1 setTitle:@"" forState:UIControlStateNormal];
            [weakSelf.btn1 setImage:image forState:UIControlStateNormal];
        });
    }
    if ([URL containsString:@"null"]||URL.length<4) {
        _imageName = @"";
    }else{
        _imageName = URL;
    }
}

#pragma mark - gesture actions
- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    [self.view endEditing:YES];
}



-(void)setText:(NSString *)text andTF:(UITextField *)textField andIndex:(NSInteger)index andPlaceholder:(NSString *)placeholder andKeyboardType:(UIKeyboardType)Type{
    CGFloat T = 215+ 20 + index*90;
    
    UILabel * lab = [[UILabel alloc]init];
    [self.SC addSubview:lab];
    [self setLab:lab withColor:RGB(30, 63, 88) andFont:12 andText:text andTextAlignment:NSTextAlignmentLeft];
    lab.frame=CGRectMake(15, T, 200, 30);
    
    
    [self.SC addSubview:textField];
    [self setTextField:textField WithPlaceholder:placeholder and:Type];
    textField.frame=CGRectMake(15, T+20, G_SCREENWIDTH-30, 40);
    
    UIView * line = [[UIView alloc]init];
    line.backgroundColor=RGB(231, 235, 238);
    [self.SC addSubview:line];
    line.frame=CGRectMake(15, T+20+39, G_SCREENWIDTH-30, 1);
    
}

-(void)setLab:(UILabel *)lab withColor:(UIColor *)color andFont:(CGFloat)font andText:(NSString *)text andTextAlignment:(NSTextAlignment)textAlignment{
    lab.text=text;
    lab.textColor=color;
    lab.font=[UIFont systemFontOfSize:font];
    lab.textAlignment=textAlignment;
}

-(void)setTextField:(UITextField*)textField WithPlaceholder:(NSString *)placeholder and:(UIKeyboardType)type  {
    
    
    textField.placeholder=placeholder;
    textField.borderStyle = UITextBorderStyleNone;
    //    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    //    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.backgroundColor=[UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:15];
    textField.textColor = RGB(32, 64, 89);
    textField.textAlignment = NSTextAlignmentLeft;
    //    textField.returnKeyType = UIReturnKeyDefault;
    textField.keyboardType = type;
    [textField setValue:RGB(190, 190, 190) forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
}


-(void)textFieldDidChange:(UITextField *)textField{
    textField.text= [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
}


#pragma mark-添加收款账户
-(void)rightAction{
    /*
     * 上传图片
     */
    [self saveImage];
    
}

#pragma mark-上传二维码  // host/dir/文件名
-(void)selectedQRcode{

    [self _initPickControl];
    
}

- (void)_initPickControl {
    
    UIImagePickerController *imgPickControl = [[UIImagePickerController alloc]init];
    imgPickControl.delegate = self;
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:@"选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            imgPickControl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imgPickControl.mediaTypes = @[(NSString *)kUTTypeMovie, (NSString *)kUTTypeMPEG,(NSString *)kUTTypeImage];
            [self presentViewController:imgPickControl animated:YES completion:nil];
        }
    }];
    UIAlertAction *camearAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            imgPickControl.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imgPickControl animated:YES completion:nil];
        }
    }];
    [alertControl addAction:cancelAction];
    [alertControl addAction:photoAction];
    [alertControl addAction:camearAction];
    [self presentViewController:alertControl animated:YES completion:nil];
}


#pragma mark 图片选择协议UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSLog(@"image width:%f, height:%f", image.size.width, image.size.height);
  
    
    WS(weakSelf);
    [self GetImg:image andBlock:^(UIImage *image, NSString *imgName, NSData *ImageData) {
        [weakSelf.btn1 setImage:image forState:UIControlStateNormal];
        [weakSelf.btn1 setTitle:@"" forState:UIControlStateNormal];
        weakSelf.ImageData = ImageData;
        weakSelf.imageName = imgName;
    }];

    
    
}

#pragma mark-处理图片
-(void)GetImg:(UIImage *)image andBlock:(GetImgVSuccessBlock)block{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    // 图片名
    NSString *imageName = [NSString stringWithFormat:@"%@.jpg", [[NSUUID UUID]UUIDString]];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", imageName]];
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        
        [fileManager removeItemAtPath:imageFilePath error:&error];
        
    }
    
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:DuoLian_OSSIMGCGSIZE];
    
    [UIImageJPEGRepresentation(smallImage,DuoLian_compressionQuality) writeToFile:imageFilePath atomically:YES];
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    
    NSData *ImageData =UIImagePNGRepresentation(selfPhoto);

    imageName = [NSString stringWithFormat:@"%@/%@.jpg",[MOLoadHttpsData getCurrentTimestamp], [[NSUUID UUID]UUIDString]];

    
    block(selfPhoto,imageName,ImageData);
    
}

#pragma mark-保存图片
- (void)saveImage{
    
    if ((!self.ImageData) && (_imageName.length<1)) {
        [HUD showErrorMessage:@"请选择图片！"];
        return;
    }
    
    if (_password_textField.text.length<1) {
        [HUD showErrorMessage:@"请输入资金密码！"];
        return;
    }
    
    if (_zhanghao_textField.text.length<1) {
        [HUD showErrorMessage:@"请输入账号！"];
        return;
    }
    
    if (_name_textField.text.length<1) {
        [HUD showErrorMessage:@"请输入姓名！"];
        return;
    }

    
    if (_imageName.length>1) {
        NSDictionary * account = _dataSource.account;
        
        NSString * URL = [NSString stringWithFormat:@"%@",account[@"qrcode_url"]];
        
        [self Http_otcpayment_payment:URL];
    }else{
        [self updateToALi:self.ImageData imageName:_imageName];
    }
}



// 改变图片尺寸
-(UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    
    UIImage *newimage;
    
    if (nil == image) {
        
        newimage = nil;
        
    }
    
    else{
        
        CGSize oldsize = image.size;
        
        CGRect rect;
        
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            
            rect.size.height = asize.height;
            
            rect.origin.x = (asize.width - rect.size.width)/2;
            
            rect.origin.y =0;
            
        }
        
        else{
            
            rect.size.width = asize.width;
            
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            
            rect.origin.x =0;
            
            rect.origin.y = (asize.height - rect.size.height)/2;
            
        }
        
        UIGraphicsBeginImageContext(asize);
        
        CGContextRef context =UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [[UIColor clearColor]CGColor]);
        
        UIRectFill(CGRectMake(0,0, asize.width, asize.height));//clear background
        
        [image drawInRect:rect];
        
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
    }
    
    return newimage;
    
}




- (void)updateToALi:(NSData *)data imageName:(NSString *)imageName{
    
    AlipayOSSModel * OssModel = [AlipayOSSModel sharedAlipayOSSModel];
    
    
    NSString *endpoint = DuoLian_endPoint;//后台给的
    
    // 明文设置secret的方式建议只在测试时使用，更多鉴权模式参考后面链接给出的官网完整文档的`访问控制`章节
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:DuoLian_AccessKey secretKey:DuoLian_SecretKey];//后台给的
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 3;
    conf.enableBackgroundTransmitService = NO;
    conf.timeoutIntervalForRequest = 15;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    
    OSSClient  *client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential  clientConfiguration:conf];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.contentType=@"image/jpeg";
    put.bucketName = DuoLian_BucketName;//后台给的
    put.objectKey = imageName;
    WS(weakSelf);
    
    put.uploadingData = data; // 直接上传NSData字节
    
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    OSSTask * putTask = [client putObject:put];
    [HUD showProgress:@"" inView:self.bgView];
    [putTask continueWithBlock:^id(OSSTask *task) {
        [HUD dismissInView:weakSelf.bgView];
        task = [client presignPublicURLWithBucketName:DuoLian_BucketName withObjectKey:imageName];
        if (!task.error) {
            NSString *qrcode_url = [NSString stringWithFormat:@"%@",task.result];
            
            [weakSelf Http_otcpayment_payment:qrcode_url];
            
        } else {
            
            [HUD showErrorMessage:@"图片上传失败!"];
            NSLog(@"upload object failed, error: %@" , task.error);
            
            
        }
        return nil;
    }];
    
    //        [putTask waitUntilFinished];//这个时sdk给的用于多张图片上传时 加上它时只有第一个走了成功或者失败第二个才会走 。相当于等待串行。
    
    
    
}


/*
 添加用户收款方式
 
 1、接口地址
 
 请求方式：post
 请求接口：otcpayment/payment
 是否登录：是
 2、接口请求参数（支付宝/微信支付）
 
 参数名    参数类型    含义    备注
 payment_id    整型    收款方式id
 paytype_id    整型    支付方式id
 account    字符串    账户号码
 qrcode_url    字符串    二维码上传地址
 asset_password    字符串    用户资产密码    lenth >= 6
 
 */
#pragma mark- 更新用户收款方式
-(void)Http_otcpayment_payment:(NSString *)qrcode_url{
    
    NSString * URL = [NSString stringWithFormat:@"%@otcpayment/updatepayment/",DEFAULTSEVERBASEURL];
    
    WS(weakSelf);
    
    NSDictionary * Dic =@{
                          @"payment_id":_dataSource.ID,
                          @"paytype_id":_dataSource.paytype_id,
                          @"account":_zhanghao_textField.text,
                          @"qrcode_url":qrcode_url,
                          @"asset_password":_password_textField.text,
                          @"name":_name_textField.text,
                          @"access_token":[LoginModel GetValue:DL_token]
                          };
    
    [HUD showProgress:@"" inView:self.bgView];
    
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.bgView];
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        if ([code isEqualToString:@"0"]) {
            
            [HUD showSuccessMessage:msg];

            [self performSelector:@selector(delayMent) withObject:nil afterDelay:2.0];
            
        }else{
            [HUD showErrorMessage:msg];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        
        [HUD dismissInView:weakSelf.bgView];
        
    }];
}

-(void)delayMent{
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[AccountViewController class]]) {
            
            AccountViewController *A =(AccountViewController *)controller;
            [self.navigationController popToViewController:A animated:YES];
            
        }
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end



























































